﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using LinFu.IoC.Configuration;

namespace CoreEx.Database.Persistence.Implementation
{
    [Implements(typeof(IPropertyPicker))]
    public class PropertyPicker : IPropertyPicker
    {
        public IEnumerable<PropertyInfo> ChooseProxyPropertiesFrom(Type baseType, IEnumerable<Type> baseInterfaces)
        {
            var results = new HashSet<PropertyInfo>();



            var baseProperties = from property in baseType.GetProperties()
                                 where property.GetGetMethod().IsVirtual && !property.GetGetMethod().IsFinal && !property.GetGetMethod().IsPrivate
                                 select property;

            // Add the virtual methods defined
            // in the base type
            foreach (var method in baseProperties)
            {
                if (!results.Contains(method))
                    results.Add(method);
            }

            var interfaceMethods = from currentInterface in baseInterfaces
                                   from property in currentInterface.GetProperties()
                                   where property.GetGetMethod().IsPublic && property.GetGetMethod().IsVirtual &&
                                         !property.GetGetMethod().IsFinal && !results.Contains(property)
                                   select property;

            // Add the virtual methods defined
            // in the interface types
            foreach (var method in interfaceMethods)
            {
                results.Add(method);
            }

            return results;
        }
    }
}
